#ifndef FENGGO_AI_AI
#define FENGGO_AI_AI

#include <dlfcn.h>
#include "FengGo.hpp"

namespace magicube{

extern long nowBoard[] ;

class AI{
private:
	char * sCols ;   // 当前终端的列数
	char * sLines;    // 当前终端的行数
public:
	AI(char pCols[], char pLines[]){
		sCols  = pCols ;
		sLines = pLines;
	}
	AI(void){}
	~AI(void){}
public:
	int AISearch(){
		
		toSO();
		
		return 0;
	}

private:
	int toSO(){
		char sDepth[2 +1];      //运算深度
		int  iDepth;            //运算深度
		char sSoFile[255 + 1];  //so文件
		char sBuf   [255 + 1];  //so文件
		//
		void * handle;
		int  devid = 0;
		
		memset(sDepth, 0x00, sizeof(sDepth));
		AIutil.getINI((char*)("[SEARCh]"), (char*)("FengGO_searchdepth="), sDepth);
		iDepth = atoi(sDepth);
		for(int i = 0; i < iDepth; i++){
			memset(sBuf   , 0x00, sizeof(sBuf   ));
			memset(sSoFile, 0x00, sizeof(sSoFile));
			AIutil.getINI((char*)("[SEARCh]"), (char*)("FengGO_search1="), sBuf);
			sprintf(sSoFile, "%s%s", getenv("HOME"), sBuf);

			handle = dlopen(sSoFile, RTLD_LAZY);
			if(handle == NULL){
				AIlog.ErrLog("打开so错误\n");
				return -1;
			}
			typedef int (*search)(long*, char*, char*);
			const char *type_error = dlerror();
			if(type_error){
				AIlog.ErrLog("定义类型错误[%s]\n", type_error);
				dlclose(handle);
				return -1;
			}
			search Search = (search) dlsym(handle,"Search");
			const char *dlsym_error = dlerror();
			if(dlsym_error){
				AIlog.ErrLog("调用so函数错误[%s]\n", dlsym_error);
				dlclose(handle);
				return -1;
			}
			devid = Search(nowBoard, sCols, sLines);
			if(devid >= 0)
			{
				AIlog.ErrLog("SO计算结果[%s][%s]\n", sCols, sLines);
			}else
			{
				//std::cout<<"fail!\n";
			}
			
			dlclose(handle);
		}
		
		return 0;
	}

};
}
#endif
